<template>
  <div class="contribute">
    <div class="form">
      <div class="title">
        <span>创意投稿</span>
      </div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 1000px"
        :model="submit"
        status-icon
        class="demo-ruleForm"
        require-asterisk-position="right"
      >
        <el-form-item
          label="Hi，请输入您对网页的建议或问题反馈吧～"
          required
          :error="textError"
        >
          <el-input
            v-model="submit.contributeText"
            style="width: 1000px"
            :rows="10"
            type="textarea"
            maxlength="225"
            show-word-limit
            placeholder="请描述您对网页创新的提议或者有什么问题，如某个功能不好使用，有更好的改进方式（5个字以上）"
            resize="none"
            @blur="detectionText(submit.contributeText)"
          />
        </el-form-item>
        <el-form-item
          label="上传创新文件（或者问题图片）的压缩包或者md说明文档，能让你的建议更快的被接受哦"
          required
          :error="fileError"
        >
          <el-upload
            class="upload"
            drag
            accept="zip"
            :auto-upload="false"
            :on-change="onChange"
            :limit="1"
            :file-list="fileList"
            ref="uploadRef"
          >
            <div class="el-upload__text">
              将文件拖拽至此或<em>点击此处上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">zip 文件或 md 文件大小不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="您的邮箱" :error="emailError">
          <br />
          <el-input
            v-model="submit.email"
            style="width: 240px"
            placeholder="请输入邮箱"
            @blur="detectionEmail()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitContribute">
            提交投稿
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { submitContributeAndZip } from '@/apis/contribute'
import router from '@/router'

const submit = reactive({})
const fileList = reactive([])
const textError = ref('')
const fileError = ref('')
const emailError = ref('')
let contributeForm = new FormData()
const uploadRef = ref()

const onChange = (file, uploadFiles) => {
  if (!file.name.endsWith('.zip') && !file.name.endsWith('.md')) {
    ElMessage.error('文件类型错误')
    uploadFiles.splice(
      uploadFiles.findIndex((f) => f.uid === file.uid),
      1
    )
    return
  }
  fileList.push(uploadFiles[0])
}

const submitContribute = async () => {
  if (!detection()) {
    return
  }
  contributeForm.append('file', fileList[0].raw)
  contributeForm.append('submit', JSON.stringify(submit))
  const log = await submitContributeAndZip(contributeForm)
  console.log(log)
  if (log.code == 200) {
    ElMessage.success('上传成功')
    submit.contributeText = ''
    submit.email = ''
    fileList.splice(0, fileList.length)
    uploadRef.value.clearFiles()
  } else if (log.code == 401) {
    ElMessage.warning(' 用户未登录 ')
    router.push('/login')
  } else {
    ElMessage.error('上传失败，请重新上传')
  }
}

const detectionText = (text) => {
  if (text == null || text == undefined || text == '') {
    textError.value = '反馈不能为空'
    return false
  } else if (text.length < 5) {
    textError.value = '反馈内容至少有5个字以上'
    return false
  }
  textError.value = ''
}

const detectionFile = () => {
  if (fileList.length == 0) {
    fileError.value = '请上传文件'
    return false
  }
  fileError.value = ''
}
const detection = () => {
  detectionFile()
  detectionText(submit.contributeText)
  if (fileError.value != '') {
    ElMessage.error('请上传文件')
    return false
  } else if (textError.value != '') {
    ElMessage.error('请输入投稿内容')
    return false
  }
  if (detectionEmail() == false) {
    ElMessage.error('邮箱格式错误')
    return false
  }
  return true
}

const detectionEmail = () => {
  if (submit.email != '' && submit.email != undefined && submit.email != null) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if (!emailRegex.test(submit.email)) {
      emailError.value = '邮箱格式错误'
      return false
    }
  }
  emailError.value = ''
}
</script>

<style lang="scss" scoped>
.contribute {
  background-color: #fff;
  height: 800px;
  // margin-top: 20px;
  .form {
    width: 1040px;
    height: 100%;
    margin: 0 auto;
    // background-color: pink;
    .title {
      font-size: 25px;
      display: flex;
      justify-content: center;
    }
    .el-form-item {
      display: initial !important;
      :deep(.el-form-item__label) {
        font-size: 18px;
        margin-top: 30px;
        margin-bottom: 10px;
      }
    }
    .upload {
      width: 1000px;
      height: 180px;
      :deep(.el-upload-list) {
        margin-top: 0;
      }
    }
    :deep(.el-form-item__error) {
      margin-top: 2px;
    }
    .el-button {
      margin-top: 25px;
    }
  }
}
</style>
